// 失分明细表单交互增强
class LossDetailForm {
    constructor() {
        // 使用全局变量或默认值
        this.maxLoss = typeof MAX_ALLOWED_LOSS !== 'undefined' ? MAX_ALLOWED_LOSS : 0;
        this.init();
    }

    init() {
        this.bindEvents();
        this.initCustomKnowledgeToggle();
        this.initEnhancedSelects();
        this.initFormValidation();
        this.initAnimations();
    }

    bindEvents() {
        // 自定义知识点切换
        const toggleBtn = document.getElementById('toggle-custom-knowledge');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', (e) => this.handleCustomKnowledgeToggle(e));
        }

        // 表单提交验证
        const form = document.getElementById('lossDetailForm');
        if (form) {
            form.addEventListener('submit', (e) => this.handleFormSubmit(e));
        }

        // 实时验证
        this.bindRealTimeValidation();
    }

    initCustomKnowledgeToggle() {
        const customContainer = document.getElementById('custom-knowledge-container');
        const knowledgeSelect = document.getElementById('{{ form.knowledge_point.id_for_label }}');
        const customInput = document.getElementById('{{ form.custom_knowledge_point.id_for_label }}');

        // 初始状态检查
        if (customInput && customInput.value.trim() !== '') {
            this.showCustomKnowledgeField();
        }
    }

    handleCustomKnowledgeToggle(e) {
        e.preventDefault();
        const customContainer = document.getElementById('custom-knowledge-container');

        if (customContainer.classList.contains('d-none')) {
            this.showCustomKnowledgeField();
        } else {
            this.hideCustomKnowledgeField();
        }
    }

    showCustomKnowledgeField() {
        const customContainer = document.getElementById('custom-knowledge-container');
        const knowledgeSelect = document.getElementById('{{ form.knowledge_point.id_for_label }}');
        const toggleBtn = document.getElementById('toggle-custom-knowledge');
        const customInput = document.getElementById('{{ form.custom_knowledge_point.id_for_label }}');

        customContainer.classList.remove('d-none');
        knowledgeSelect.disabled = true;
        toggleBtn.innerHTML = '<i class="bi bi-arrow-left"></i> 使用已有知识点';

        // 添加动画效果
        customContainer.style.animation = 'fadeInUp 0.4s ease-out';

        // 自动聚焦
        setTimeout(() => {
            if (customInput) customInput.focus();
        }, 300);
    }

    hideCustomKnowledgeField() {
        const customContainer = document.getElementById('custom-knowledge-container');
        const knowledgeSelect = document.getElementById('{{ form.knowledge_point.id_for_label }}');
        const toggleBtn = document.getElementById('toggle-custom-knowledge');
        const customInput = document.getElementById('{{ form.custom_knowledge_point.id_for_label }}');

        customContainer.classList.add('d-none');
        knowledgeSelect.disabled = false;
        toggleBtn.innerHTML = '<i class="bi bi-plus-circle"></i> 添加自定义知识点';

        // 清空自定义输入
        if (customInput) customInput.value = '';
    }

    initEnhancedSelects() {
        // 为选择框添加增强样式
        const selects = document.querySelectorAll('.form-select');
        selects.forEach(select => {
            select.addEventListener('change', (e) => {
                this.addSelectAnimation(e.target);
            });
        });
    }

    addSelectAnimation(element) {
        element.style.transform = 'scale(1.02)';
        setTimeout(() => {
            element.style.transform = 'scale(1)';
        }, 150);
    }

    initFormValidation() {
        // 实时验证配置
        const inputs = document.querySelectorAll('#lossDetailForm input, #lossDetailForm select, #lossDetailForm textarea');
        inputs.forEach(input => {
            input.addEventListener('blur', (e) => this.validateField(e.target));
            input.addEventListener('input', (e) => this.clearFieldError(e.target));
        });
    }

    bindRealTimeValidation() {
        // 失分分值实时验证
        const pointsInput = document.getElementById('{{ form.points.id_for_label }}');
        if (pointsInput) {
            pointsInput.addEventListener('input', (e) => this.validatePointsInRealTime(e.target));
        }
    }

    validatePointsInRealTime(input) {
        const value = parseFloat(input.value);

        if (value > this.maxLoss) {
            this.showRealTimeError(input, `失分分值不能超过 ${this.maxLoss} 分`);
        } else {
            this.clearRealTimeError(input);
        }
    }

    showRealTimeError(input, message) {
        this.clearRealTimeError(input);

        const errorDiv = document.createElement('div');
        errorDiv.className = 'real-time-error text-danger small mt-1';
        errorDiv.innerHTML = `<i class="bi bi-exclamation-triangle"></i> ${message}`;
        errorDiv.style.cssText = `
            background: rgba(245, 101, 101, 0.1);
            padding: 0.5rem;
            border-radius: 6px;
            border-left: 3px solid #f56565;
            margin-top: 0.5rem;
        `;

        input.parentNode.appendChild(errorDiv);
        input.classList.add('is-invalid');
    }

    clearRealTimeError(input) {
        const existingError = input.parentNode.querySelector('.real-time-error');
        if (existingError) {
            existingError.remove();
        }
        input.classList.remove('is-invalid');
    }

    validateField(field) {
        // 简单的字段验证逻辑
        if (field.required && !field.value.trim()) {
            this.markFieldAsInvalid(field, '此字段为必填项');
            return false;
        }

        this.markFieldAsValid(field);
        return true;
    }

    clearFieldError(field) {
        field.classList.remove('is-invalid', 'is-valid');
        const feedback = field.parentNode.querySelector('.real-time-error');
        if (feedback) {
            feedback.remove();
        }
    }

    markFieldAsInvalid(field, message) {
        field.classList.remove('is-valid');
        field.classList.add('is-invalid');

        // 显示错误消息
        this.showRealTimeError(field, message);
    }

    markFieldAsValid(field) {
        field.classList.remove('is-invalid');
        field.classList.add('is-valid');
    }

    handleFormSubmit(e) {
        let isValid = true;
        const form = e.target;

        // 验证失分分值
        const pointsInput = document.getElementById('{{ form.points.id_for_label }}');

        if (pointsInput && parseFloat(pointsInput.value) > this.maxLoss) {
            this.showToast(`失分分值不能超过 ${this.maxLoss} 分，请调整后再提交！`, 'error');
            pointsInput.focus();
            isValid = false;
        }

        // 验证知识点选择
        const knowledgeSelect = document.getElementById('{{ form.knowledge_point.id_for_label }}');
        const customInput = document.getElementById('{{ form.custom_knowledge_point.id_for_label }}');

        if (knowledgeSelect.disabled && !customInput.value.trim()) {
            this.showToast('请输入自定义知识点名称，或切换为使用已有知识点！', 'error');
            customInput.focus();
            isValid = false;
        }

        if (!isValid) {
            e.preventDefault();
            this.addShakeAnimation(form);
        } else {
            // 添加提交动画
            this.addSubmitAnimation(form);
        }
    }

    addShakeAnimation(element) {
        element.style.animation = 'shake 0.5s ease-in-out';
        setTimeout(() => {
            element.style.animation = '';
        }, 500);
    }

    addSubmitAnimation(form) {
        const submitBtn = form.querySelector('button[type="submit"]');
        if (submitBtn) {
            submitBtn.innerHTML = '<i class="bi bi-hourglass-split"></i> 保存中...';
            submitBtn.disabled = true;
            submitBtn.classList.add('loading');
        }
    }

    showToast(message, type = 'info') {
        // 简单的toast通知实现
        const toast = document.createElement('div');
        const bgColor = type === 'error' ? 'linear-gradient(135deg, #f56565, #e53e3e)' :
                         type === 'success' ? 'linear-gradient(135deg, #48bb78, #38a169)' :
                         'linear-gradient(135deg, #4299e1, #3182ce)';

        toast.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: ${bgColor};
            color: white;
            padding: 1rem 1.5rem;
            border-radius: 12px;
            box-shadow: 0 10px 25px rgba(0,0,0,0.2);
            z-index: 9999;
            max-width: 300px;
            animation: slideInRight 0.3s ease-out;
        `;

        toast.innerHTML = `
            <div class="d-flex align-items-center gap-2">
                <i class="bi bi-${type === 'error' ? 'exclamation-triangle' : type === 'success' ? 'check-circle' : 'info-circle'}"></i>
                <span>${message}</span>
            </div>
        `;

        document.body.appendChild(toast);

        setTimeout(() => {
            toast.style.animation = 'slideOutRight 0.3s ease-in';
            setTimeout(() => {
                if (toast.parentNode) {
                    toast.parentNode.removeChild(toast);
                }
            }, 300);
        }, 4000);
    }

    initAnimations() {
        // 添加CSS动画
        const style = document.createElement('style');
        style.textContent = `
            @keyframes shake {
                0%, 100% { transform: translateX(0); }
                25% { transform: translateX(-5px); }
                75% { transform: translateX(5px); }
            }
            
            @keyframes slideInRight {
                from { transform: translateX(100%); opacity: 0; }
                to { transform: translateX(0); opacity: 1; }
            }
            
            @keyframes slideOutRight {
                from { transform: translateX(0); opacity: 1; }
                to { transform: translateX(100%); opacity: 0; }
            }
            
            .is-valid {
                border-color: #48bb78 !important;
                box-shadow: 0 0 0 3px rgba(72, 187, 120, 0.1) !important;
            }
        `;
        document.head.appendChild(style);
    }
}

// 初始化表单
document.addEventListener('DOMContentLoaded', function() {
    new LossDetailForm();
});